#!/usr/bin/env bash
#################
stop_vnc_main() {
    tmoe_vnc_env
    rm_vnc_lock
    pkill_vnc
    case "$1" in
    -non-stop-dbus)
        stopx11vnc
        ;;
    -non-stop-x11vnc) ;;
    -x11)
        stop_dbus_daemon
        stopx11vnc
        ;;
    -h | --h | --help | -help)
        cat <<-'EOF'
			-non-stop-dbus    --不停止dbus-daemon
			-non-stop-x11vnc  --不停止x11vnc
            -x11              --停止x11vnc
			-h               --获取帮助信息
		EOF
        ;;
    *)
        stopx11vnc 2>/dev/null
        stop_dbus_daemon
        stopx11vnc
        vnc_server_has_been_stopped
        ;;
    esac
}
############
stopx11vnc() {
    pkill Xvfb
    rm -fv /tmp/.X233-lock /tmp/.X11-unix/X233 2>/dev/null
}
##########
tmoe_vnc_env() {
    export USER="$(whoami)"
    export HOME="${HOME}"
    #CURRENT_PORT=$(sed -n p /usr/local/bin/startvnc | grep '\-geometry' | awk -F ' ' '$0=$NF' | cut -d ':' -f 2 | tail -n 1)
    CURRENT_PORT=$(sed -n p /usr/local/bin/startvnc | grep 'TMOE_VNC_DISPLAY_NUMBER=' | cut -d '=' -f 2 | head -n 1)
}
###########
rm_vnc_lock() {
    [[ $(command -v vncsession) ]] || vncserver -kill :${CURRENT_PORT} 2>/dev/null
    rm -vf /tmp/.X${CURRENT_PORT}-lock 2>/dev/null
    rm -vf /tmp/.X11-unix/X${CURRENT_PORT} 2>/dev/null
}
#############
rm_dbus_pid_file() {
    if [ $(command -v sudo) ]; then
        sudo rm -vf /run/dbus/pid /var/run/dbus/pid /run/dbus/messagebus.pid /run/messagebus.pid /var/run/dbus/messagebus.pid /var/run/messagebus.pid 2>/dev/null
    else
        su -c "rm -vf /run/dbus/pid /var/run/dbus/pid /run/dbus/messagebus.pid /run/messagebus.pid /var/run/dbus/messagebus.pid /var/run/messagebus.pid 2>/dev/null"
    fi
}
############
stop_dbus_daemon() {
    case ${TMOE_CHROOT} in
    true)
        if [ -e "/run/dbus/pid" ]; then
            DBUS_PID=$(sed -n p /run/dbus/pid)
            printf "%s\n" "kill -9 ${DBUS_PID}"
            kill -9 ${DBUS_PID}
            rm_dbus_pid_file
        fi
        ;;
    esac
    #pkill dbus
}
##########
pkill_vnc() {
    pkill -9 Xtightvnc
    pkill -9 Xtigertvnc
    pkill -9 Xvnc
    pkill -9 vncsession
}
#############
vnc_server_has_been_stopped() {
    if [ ! "$(pgrep Xvnc)" ]; then
        printf "%s\n" "已停止VNC服务！"
        printf "%s\n" "VNC server has been terminated."
    fi
}
#################
stop_vnc_main "$@"
